<?php

/*============================================
Classe Iabus
============================================*/

class Iabus extends ModelObject{

	protected static $cached_object_list= array();
	protected $BUS_ID;
	protected $BUS_NAME;
	protected $BUS_LABEL;
	protected $BUS_TYPE;
	protected $BIT_RATE;
	protected $MONITORING_STATUS;
	protected $BUS_TIMEOUT;

	protected function __construct( $BUS_ID,$BUS_NAME,$BUS_LABEL,$BUS_TYPE,$BIT_RATE,$MONITORING_STATUS,$BUS_TIMEOUT){
		try{
			
			$this->BUS_ID = $BUS_ID;
			$this->BUS_NAME = $BUS_NAME;
			$this->BUS_LABEL = $BUS_LABEL;
			$this->BUS_TYPE = $BUS_TYPE;
			$this->BIT_RATE = $BIT_RATE;
			$this->MONITORING_STATUS = $MONITORING_STATUS;
			$this->BUS_TIMEOUT = $BUS_TIMEOUT;
		}
		catch(Excpetion $e){
			throw new Exception("La construction de l'objet de type get_class($this) a échouée",0,$e);
		}
	}

	public function getBUSID(){
		return $this->BUS_ID;
	}

	public function getBUSNAME(){
		return $this->BUS_NAME;
	}

	public function getBUSLABEL(){
		return $this->BUS_LABEL;
	}

	public function getBUSTYPE(){
		return $this->BUS_TYPE;
	}

	public function getBITRATE(){
		return $this->BIT_RATE;
	}

	public function getMONITORINGSTATUS(){
		return $this->MONITORING_STATUS;
	}

	public function getBUSTIMEOUT(){
		return $this->BUS_TIMEOUT;
	}

	public function setBUSNAME( $BUS_NAME){
		try{
			$temp = $this->BUS_NAME;
			if($this->BUS_NAME !== $BUS_NAME){
				$this->BUS_NAME = $BUS_NAME;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->BUS_NAME = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setBUSNAME() a échouée",0,$e);
		}
	}

	public function setBUSLABEL( $BUS_LABEL){
		try{
			$temp = $this->BUS_LABEL;
			if($this->BUS_LABEL !== $BUS_LABEL){
				$this->BUS_LABEL = $BUS_LABEL;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->BUS_LABEL = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setBUSLABEL() a échouée",0,$e);
		}
	}

	public function setBUSTYPE( $BUS_TYPE){
		try{
			$temp = $this->BUS_TYPE;
			if($this->BUS_TYPE !== $BUS_TYPE){
				$this->BUS_TYPE = $BUS_TYPE;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->BUS_TYPE = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setBUSTYPE() a échouée",0,$e);
		}
	}

	public function setBITRATE( $BIT_RATE){
		try{
			$temp = $this->BIT_RATE;
			if($this->BIT_RATE !== $BIT_RATE){
				$this->BIT_RATE = $BIT_RATE;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->BIT_RATE = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setBITRATE() a échouée",0,$e);
		}
	}

	public function setMONITORINGSTATUS( $MONITORING_STATUS){
		try{
			$temp = $this->MONITORING_STATUS;
			if($this->MONITORING_STATUS !== $MONITORING_STATUS){
				$this->MONITORING_STATUS = $MONITORING_STATUS;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->MONITORING_STATUS = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setMONITORINGSTATUS() a échouée",0,$e);
		}
	}

	public function setBUSTIMEOUT( $BUS_TIMEOUT){
		try{
			$temp = $this->BUS_TIMEOUT;
			if($this->BUS_TIMEOUT !== $BUS_TIMEOUT){
				$this->BUS_TIMEOUT = $BUS_TIMEOUT;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->BUS_TIMEOUT = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setBUSTIMEOUT() a échouée",0,$e);
		}
	}

	public static function create( $BUS_ID,$BUS_NAME,$BUS_LABEL,$BUS_TYPE,$BIT_RATE,$MONITORING_STATUS,$BUS_TIMEOUT){
		try{
			$iabus = new Iabus($BUS_ID, $BUS_NAME, $BUS_LABEL, $BUS_TYPE, $BIT_RATE, $MONITORING_STATUS, $BUS_TIMEOUT);
			$iabus->insert();
			Iabus::cacheObject($iabus);
			return $iabus;
		}
		catch(Excpetion $e){
			throw new Exception("La création de l'objet de type Iabus a échouée",0,$e);
		}
	}

	public static function get( $BUS_ID){
		$dbh = SingletonPDO::getInstance();
		try{
			if(is_null($BUS_ID) || $BUS_ID === "") {
				return null;
			}
			if(Iabus::existsInCache($BUS_ID)) {
				return Iabus::getFromCache($BUS_ID);
			}
			$dbh->beginTransaction();
			$sql= 'SELECT * FROM `iabus` WHERE `BUS_ID` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$BUS_ID));
			if ($row = $stmt->fetch()){
				$iabus = new Iabus( $row['BUS_ID'],$row['BUS_NAME'],$row['BUS_LABEL'],$row['BUS_TYPE'],$row['BIT_RATE'],$row['MONITORING_STATUS'],$row['BUS_TIMEOUT']);
				$iabus->id =  $row['BUS_ID'];
				$dbh->commit();
				Iabus::cacheObject($iabus);
				return $iabus;
			}
			else {
				$dbh->commit();
				return null;
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récupération de l'objet ayant l'id ". $BUS_ID . " a échouée",0,$e);
		}
	}

	protected function update(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql='UPDATE `iabus` SET `BUS_NAME` = :BUS_NAME, `BUS_LABEL` = :BUS_LABEL, `BUS_TYPE` = :BUS_TYPE, `BIT_RATE` = :BIT_RATE, `MONITORING_STATUS` = :MONITORING_STATUS, `BUS_TIMEOUT` = :BUS_TIMEOUT WHERE `BUS_ID` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':BUS_NAME'=>$this->BUS_NAME, ':BUS_LABEL'=>$this->BUS_LABEL, ':BUS_TYPE'=>$this->BUS_TYPE, ':BIT_RATE'=>$this->BIT_RATE, ':MONITORING_STATUS'=>$this->MONITORING_STATUS, ':BUS_TIMEOUT'=>$this->BUS_TIMEOUT, ':id'=>$this->id));
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La modification de l'objet de type ".get_class($this)." ayant l'id ". $this->id . " a échouée",0,$e);
		}
	}

	public function delete(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql = 'DELETE FROM `iabus` WHERE `BUS_ID` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$this->id));
			Iabus::removeObjectFromCache($this->id);
			$this->id = null;
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de l'objet de type ".get_class($this)." ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	protected function insert(){
		$dbh = SingletonPDO::getInstance();
		try{
			if (is_null($this->id)) {
				$dbh->beginTransaction();
				$sql='INSERT INTO `iabus` ( `BUS_NAME`, `BUS_LABEL`, `BUS_TYPE`, `BIT_RATE`, `MONITORING_STATUS`, `BUS_TIMEOUT`) VALUES (:BUS_NAME, :BUS_LABEL, :BUS_TYPE, :BIT_RATE, :MONITORING_STATUS, :BUS_TIMEOUT)';
				$stmt = $dbh->prepare($sql);
				$stmt->execute(array(':BUS_NAME'=>$this->BUS_NAME, ':BUS_LABEL'=>$this->BUS_LABEL, ':BUS_TYPE'=>$this->BUS_TYPE, ':BIT_RATE'=>$this->BIT_RATE, ':MONITORING_STATUS'=>$this->MONITORING_STATUS, ':BUS_TIMEOUT'=>$this->BUS_TIMEOUT));
				$this->id = $dbh->lastInsertId();
				$dbh->commit();
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("L'insertion de l'objet de type ".get_class($this)." a échouée",0,$e);
		}
	}

	public static function getAll( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql = 'SELECT * FROM `iabus`';
			$sql .= self::generateWhereClause($search_params);
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = null;
				if(Iabus::existsInCache($row['BUS_ID'])){
					$obj = Iabus::getFromCache($row['BUS_ID']);
				}
				else{
					$obj = new Iabus( $row['BUS_ID'],$row['BUS_NAME'],$row['BUS_LABEL'],$row['BUS_TYPE'],$row['BIT_RATE'],$row['MONITORING_STATUS'],$row['BUS_TIMEOUT']);
				}
				if(!is_null($obj)){
					$obj->id = $row['BUS_ID'];
					Iabus::cacheObject($obj);
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récuperation de la liste d'objets de type Iabus a échouée",0,$e);
		}
	}

	public static function getCount( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql = 'SELECT count(*) as count FROM `iabus`';
			$sql .= self::generateWhereClause($search_params);
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$stmt->execute($array);
			$count = $stmt->fetch();
			$dbh->commit();
			return $count['count'];
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récuperation de la liste d'objets de type Iabus a échouée",0,$e);
		}
	}

	public static function deleteAll( $search_params = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql_delete = 'DELETE FROM `iabus`';
			$sql_select = 'SELECT BUS_ID FROM `iabus`';
			$sql_delete .= self::generateWhereClause($search_params);
			$sql_select .= self::generateWhereClause($search_params);
			$stmt_delete = $dbh->prepare($sql_delete);
			$stmt_select = $dbh->prepare($sql_select);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$var_select = $stmt_select->execute($array);
			$tab_to_delete_objects = $stmt_select->fetchAll();
			if(sizeof($tab_to_delete_objects) > 0){
				$var_delete = $stmt_delete->execute($array);
				foreach($tab_to_delete_objects as $ind => $row){
					$existing_object = Iabus::getObjectFromCache($row['BUS_ID']);
					if(!is_null($existing_object)){
						$existing_object->id = null;
						Iabus::removeObjectFromCache($row['BUS_ID']);
					}
				}
			}
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de la liste d'objets de type Iabus a échouée",0,$e);
		}
	}

	/*fonction de jointure*/
	public function getListIainstruments( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$objs = array();
			$sql = 'SELECT `DEVICE_NAME` FROM `iainstruments`';
			$where = self::generateWhereClause($search_params);
			if($where === ""){
				$sql .= $where.' WHERE `BUS_ID` = :id';
			}
			else{
				$sql .= $where.' AND `BUS_ID` = :id';
			}
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$array[':id'] = $this->id;
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = Iainstruments::get($row['DEVICE_NAME']);
				if(!is_null($obj)){
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La recuperation de la liste d'objets de type Iainstruments liés à l'objet de type Iabus ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

}